<?php
/* START OF NOTES

 -- Permissions:
    $download_dir = 775
    $cookie basedir = 777

 -- Other requirements:
    Set $download_dir to writeable directory, mounted to uTorrent hot folder.

 -- TO DO
    Display message if no torrents found.
    Loading screen on search.
    Successful torrent check.
    Logout button (delete cookie and refresh).
    Put HTML forms in functions.
    Display number of failed logins before ban.
    Add check using file_exists() for downloaded torrent.
    Add script password field to login and/or search.
    Delete cookie after set time period?

END OF NOTES */

// Variables.
$script_name = $_SERVER['PHP_SELF'];
$server_path = $_SERVER['DOCUMENT_ROOT'];
$download_dir = __DIR__ . "/downloads";
$cookie = "/tmp/funfile.cookie";

/* NOT YET WORKING
// Make sure '/tmp' directory exists and is writable.
if (!is_dir("/tmp")) { mkdir("/tmp"); }
if (!is_writable("/tmp")) { chmod("/tmp", 0777); }

// Same for 'download_dir'.
if (!is_dir($download_dir)) { mkdir($download_dir); }
if (!is_writable($download_dir)) { chmod($download_dir, 0777); }
NOT YET WORKING */

// Formatting start.
?>

<style>
a:link {color:#cc3300;}
a:visited {color:#cc3300;}
a:hover {color:#cc3300;}
a:active {color:#cc3300;}
</style>
<center>
<br /><br /><br />
<body bgcolor="#660000">
<font size="2", color="#ff3300", face="Courier">

<?php // Formatting end.

// Start login condition.
if (!file_exists($cookie) && empty($_POST) && empty($_GET)) { ?>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><br><br><br>
<form action="<?php $script_name ?>" method="post" style="color: #cc3300; font-family: Courier; font-size: 12px; background-color: #660000;" size="10" maxlength="30">
  <input type="text" name="user"><br />
  <input type="password" name="pass"><br />
  <input type="submit" value="You know what to do.">
</form>

<?php
die();
} else if (!file_exists($cookie) && !empty($_POST) && empty($_GET)) {
// User account information.
$ffuser = $_POST['user'];
$ffpass = $_POST['pass'];

// Initialize curl session.
$ch_l = curl_init();

// Curl options.
curl_setopt($ch_l, CURLOPT_URL, "https://www.funfile.org/takelogin.php");
curl_setopt($ch_l, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch_l, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch_l, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch_l, CURLOPT_COOKIEJAR, "$cookie");
curl_setopt($ch_l, CURLOPT_RETURNTRANSFER, true);

// Curl set POST data.
$data_l = array('returnto' => '/',
              'username' => $ffuser,
              'password' => $ffpass,
              'login'    => 'Login'
              );

curl_setopt($ch_l, CURLOPT_POST, 1);
curl_setopt($ch_l, CURLOPT_POSTFIELDS, $data_l);

// Execute curl process.
$suppress = curl_exec($ch_l);

// Close session.
curl_close($ch_l);

    // Start secondary login condition.
    if (!file_exists($cookie)) { ?>
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><br><br><br>
      <form action="<?php $script_name ?>" method="post" style="color: #cc3300; font-family: Courier; font-size: 12px; background-color: #660000;" size="10" maxlength="30">
        <input type="text" name="user"><br />
        <input type="password" name="pass"><br />
        <input type="submit" value="You know what to do."><br /><br />
        <font color="red">Login failed.</font>
      </form>
    <?php
    die();
    // End secondary login condition.
    }

// End login condition.
}

// Start search condition.
if (!isset($_POST['search_string']) && empty($_GET)) { ?>

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><br><br><br>
<form action="<?php $script_name ?>" method="post" style="color: #cc3300; font-family: Courier; font-size: 12px; background-color: #660000;" size="10" maxlength="30">
  <input type="text" name="search_string"><br />
  <select name="id">
    <option value="0">All</option>
    <option value="45">0Day</option>
    <option value="44">Anime</option>
    <option value="22">Applications</option>
    <option value="43">Audio Books</option>
    <option value="27">Ebook</option>
    <option value="4">Games</option>
    <option value="40">Miscellaneous</option>
    <option value="19">Movies</option>
    <option value="6">Music</option>
    <option value="31">Portable</option>
    <option value="7">TV</option>
  </select>
<!--  <input type="submit" value="Search"> -->
</form>

<?php
die();
} else if (empty($_GET)) { // Once $search_string is set, do search. ?>

<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

<?php
// Create variables from POST data.
$search_string = urlencode($_POST['search_string']);
$search_id = $_POST['id'];

// Initialize curl session.
$ch_s = curl_init();

// Curl options.
curl_setopt($ch_s, CURLOPT_URL, "https://www.funfile.org/browse.php?search=$search_string&sect=search&swin=title&cat=$search_id&scat%5B%5D=");
curl_setopt($ch_s, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch_s, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch_s, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch_s, CURLOPT_COOKIEFILE, "$cookie");
curl_setopt($ch_s, CURLOPT_RETURNTRANSFER, true);

// Execute curl process and store in array "results".
$results = curl_exec($ch_s);
$results_array = explode("\n", $results);

// Relative .torrent paths.
$torrent_paths = preg_grep("*\.torrent*", explode("\n", $results));

// Keys from $results containing torrents.
$torrent_keys = array_keys($torrent_paths);

// Loop through $torrent_keys.
foreach ($torrent_keys as $t_key) {

    // Create and print the download link.
    $relative_url = preg_grep("*\.torrent*", explode("\"", $results_array[$t_key]));
    $display_name = explode("/", $relative_url[5]);
    print "<a href=\"http://" . $_SERVER['SERVER_NAME'] . ":" . $_SERVER['SERVER_PORT'] . $script_name . "?id=" . $display_name[1] . "&name=" . $display_name[2] . "\">" . urldecode($display_name[2]) . "</a><br />\n";

    // Print the age of the torrent.
    $torrent_age = strip_tags($results_array[$t_key + 4]);
    print "$torrent_age\t";

    // Print the size of the torrent.
    $torrent_size = strip_tags($results_array[$t_key + 6]);
    print "$torrent_size<br /><br />\n";

}

// Close session.
curl_close($ch_s);

// End search condition.
die();

// Start download condition.
} else if (!empty($_GET)) {

$id = $_GET['id'];
$filename = $_GET['name'];
$remote_file = "https://www.funfile.org/download.php/" . $id . "/" . $filename;
$local_file = "$download_dir" . "/" . "$filename";
$handle = fopen("$local_file.download", 'w+');

// Initalize curl session.
$ch_d = curl_init();

// Curl options.
curl_setopt($ch_d, CURLOPT_URL, $remote_file);
curl_setopt($ch_d, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch_d, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch_d, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch_d, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch_d, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch_d, CURLOPT_FILE, $handle);

// Execute download.
curl_exec($ch_d);

// Close download session.
curl_close($ch_d);

// Close file handler.
fclose($handle);

// Rename downloaded file.
rename("$local_file.download", "$local_file");

// Back to search.
print "<script>window.location = '" . $script_name . "'</script>";

// End download condition.
}

// Uh ohz.
print "If you can read this, something went horribly wrong!";

?>
